import RequestType from '../model/RequestType';
import auto_load from '../auto_load/auto_load';
import controRoute from '../route/RouterHandler';
import pars_route from '../route/RouterPars';
import run_route from '../route/RouterPars'
import color from '../utils/Color';
import errorCatch from '../entrance/event/errorCatch';
import sugar from '../core/sugar'
import gem_console from './console'

global.monitor={};
//监控所有的监控器
export = async function monitor({Controller="",route_arr=[],annotation=[]}:{annotation:Array<string>,Controller:string,route_arr:string[]},start:boolean=true){
  if(!start)return
  //=========================================================监控 <控制器>
  await monitor_controller(Controller);

  //=========================================================监控 <路由文件>
  await monitor_rout(route_arr);

  //=========================================================监控 <注解区>
  await monitor_annotation(annotation)
}


/**
 * 监控控制器
 */
async function monitor_controller(controller_path){
  await sugar.watch(controller_path,{
    // 监控规则
    rules:(path:string)=>path.endsWith(".js") || path.endsWith(".ts")
  },async (type:string,filepath:string)=>{
    try{
      // 这个控制器文件被更改
      switch (type){
        // 控制器被更改
        case "change":{}
        // 控制器被删除
        case "delete":{
          gem_console.time();        
          //重新加载所有的路由文件
          //重新解析路由
          await run_route.init();
          gem_console.timeEnd();
          break;
        }
        // 控制器被重命名
        case "rename":{}
      }
    }catch(err){
      console.log(err.toString());
      errorCatch(err,filepath)
    }
  })
}

/**
 * 监控相应的路由文件
 * 重新解析路由
 */
async function monitor_rout(route_arr:string[]){
  await sugar.watch(route_arr,async (type:string,path:string)=>{
    try{
      if(type === 'change'){
        gem_console.time();
        // 重新加载这个路由文件
        await loader(path,true);
        // 合并文件
        await run_route.mergeRout();
        gem_console.timeEnd();
      }  
    }catch(err){
      console.log(err.toString());
      errorCatch(err,path)
    }
  });  
}

/**
 * 监控注解区域
 */
async function monitor_annotation(annotation:Array<string>){
  
  await sugar.watch(annotation,{
    // 监控js文件
    rules:async (path:string)=>path.endsWith(".js"),
    hotDeployment:true
    //进行监控
  },async ( type ,filepath)=>{
    try{
      //重新加载这个文件的注解 如果这个文件是是路由的就清空 清空有可能是被删除的api
      if(controRoute.getUnStaticRoute(filepath)){
        controRoute.addUnStaticRoute(filepath,new RequestType())
        // 合并路由
        pars_route.mergeRout();
      }
      // 运行注解
      await auto_load(filepath,()=>{
          console.log(color("绿色","LOAD"),"Annotations "+color("蓝色",filepath))
      })
    }catch(err){
      console.log(err.toString())
      console.log(err)
    }
    
})
}